package servlet;

import bean.Product;
import service.ProductService;

import javax.servlet.annotation.WebServlet;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.ArrayList;
import java.util.List;

@WebServlet("/product")
public class ProductServlet extends BaseServlet {
   private ProductService ps=new ProductService();
   public void findAllProduct(HttpServletRequest req, HttpServletResponse resp)throws Exception{
       List<Product> list = ps.findAllProduct();
        req.setAttribute("plist",list );
        req.getRequestDispatcher("product.jsp").forward(req,resp );

   }
   public void findProductByPid(HttpServletRequest req, HttpServletResponse resp)throws Exception{
       String pid = req.getParameter("pid");
       Product product = ps.findfindProductByPid(Integer.parseInt(pid));
       HttpSession session = req.getSession();
       session.setMaxInactiveInterval(60*60);
       Cookie cookie = new Cookie("JSESSIONID",session.getId());
        cookie.setMaxAge(60*60);
        resp.addCookie(cookie);
        List<Product>list=(List<Product>)session.getAttribute("list");
        if (list==null){
            list=new ArrayList<>();
        }
        list.add(product);
        session.setAttribute("list",list );
        resp.sendRedirect("trolley.jsp");
   }
}
